package com.quectel.dms.controller.hik;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.base.Preconditions;
import com.quectel.business.common.device.DeviceExtraAttrCls;
import com.quectel.business.dms.AccessorUtils;
import com.quectel.business.dms.application.ApplicationAccessConf;
import com.quectel.business.dms.application.access.accessor.im.AbstractIntelligentMonitorAccessor;
import com.quectel.constant.core.eventrecord.AiEventRecordConstants;
import com.quectel.core.module.ai.dto.mongo.MongoAiEventRecordDto;
import com.quectel.core.module.application.dto.ApplicationDto;
import com.quectel.core.module.application.service.ApplicationService;
import com.quectel.core.module.device.dto.DeviceDto;
import com.quectel.core.module.device.service.DeviceService;
import com.quectel.dms.controller.BaseController;
import com.quectel.sdk.hikisc.HikClientBuilder;
import com.quectel.sdk.hikisc.constant.HikIscConstants;
import com.quectel.sdk.hikisc.monitor.MonitorClient;
import com.quectel.sys.module.sys.service.SysConfigService;
import com.quectel.util.client.minio.MinIOClient;
import com.quectel.util.common.*;
import com.quectel.util.kit.MinIOUtils;
import com.quectel.util.kit.StorageKit;
import com.quectel.util.redis.RedisUtils;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.quectel.sdk.hikisc.constant.HikIscConstants.EventEnum.HIGH_TOSS_ACT;
import static com.quectel.sdk.hikisc.constant.HikIscConstants.EventEnum.REGIONAL_INVASION;

/**
 * 海康isc平台消息接收
 *
 * @author rananxin
 * @email: ryan.ran@quectel.com
 * @date 2021/11/18 4:04 下午
 */
@RestController
@RequestMapping("hikIscCollect")
@Tag(name = "HikIscCollectController")
@Slf4j
public class HikIscCollectController extends BaseController {

    @DubboReference
    private SysConfigService sysConfigService;
    @DubboReference
    private DeviceService deviceService;
    @DubboReference
    private ApplicationService applicationService;

    @PostMapping("eventRcv/{callBackPath}")
    public Response<Object> eventRcv(@PathVariable String callBackPath, @RequestBody String data) {
        HikIscConstants.EventEnum eventEnum = HikIscConstants.EventEnum.getEnumByPath(callBackPath);
        if (eventEnum == null) {
            return Response.ok();
        }

        switch (eventEnum) {
            case FACE_AUTH_PASSD:
                faceAuthPassd(data);
                break;
            case HIGH_TOSS_ACT:
                highTossAct(data, HIGH_TOSS_ACT);
                break;
            case REGIONAL_INVASION:
                regionalInvasion(data, REGIONAL_INVASION);
                break;
            case LICENSE_PLATE_CAPTURE:
                licensePlateCapture(data);
                break;
            case FACE_CAPTURE:
                faceCapture(data);
                break;
            case VIS_FACE_OPEN_LOCK:
                visFaceOpenLock(data);
                break;
            case PARKING_LOT_ADMISSION2:
                villageingLotAdmission(data);
                break;
            case PARKING_LOT_APPEARANCE2:
                villageingLotAppearance(data);
                break;
            default:
                break;
        }
        log.info("海康 {} 订阅事件回调 path {} data {} 时间 {}", HikIscConstants.EventEnum.getNameByPath(callBackPath)
                , callBackPath, data, DateUtils.getCurrentDateStr(DateUtils.FormatType.COMMON));

        return Response.ok();
    }

    private void faceAuthPassd(String data) {
//        JSONObject jsonObject = JacksonUtils.parse(data);
//        JSONArray jsonArray =
//                jsonObject.getJSONObject("params").getJSONArray("events");
//
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
//
//        for (Object o : jsonArray) {
//            JSONObject json = (JSONObject) o;
//            String deviceUniqueId = json.getString("srcParentIndex");
//            List<DeviceDto> deviceDtos = deviceService.selectCacheByUniqueId(deviceUniqueId);
//
//            if (deviceDtos != null && deviceDtos.size() > 0) {
//
//                for (DeviceDto deviceDto : deviceDtos) {
//                    ApplicationDto ApplicationDto = applicationService.selectCacheById(deviceDto.getApplicationId());
//                    if (ApplicationDto == null) {
//                        continue;
//                    }
//                    try {
//                        JSONObject personDataJson = json.getJSONObject("data");
//                        String extEventPictureURL = personDataJson.getString("ExtEventPictureURL");
//                        String svrIndexCode = personDataJson.getString("svrIndexCode");
//                        String url = null;
//                        try {
//                            url = hikIscConfAccessorComponent.getPictures(ApplicationDto, svrIndexCode, extEventPictureURL);
//                        } catch (Exception e) {
//                            log.error("hik门禁出入记录抓拍获取异常", e);
//                        }
//                        String extEventPersonNo = personDataJson.getString("ExtEventPersonNo");
//
//                        PersonAccessRecordDto accessRecordDto = new PersonAccessRecordDto();
//                        DeviceFaceOrderDto deviceFaceOrderDto = deviceFaceOrderService.selectByDeviceIdAndFaceCode(deviceDto.getId(), extEventPersonNo);
//                        if (deviceFaceOrderDto != null) {
//                            if (deviceFaceOrderDto.getType().equals((byte)1)) {
//                                HouseHoldDto houseHoldDto = houseHoldService.selectById(deviceFaceOrderDto.getHouseholdId());
//                                if (houseHoldDto != null) {
//                                    accessRecordDto.setUserId(houseHoldDto.getId());
//                                    accessRecordDto.setName(houseHoldDto.getName());
//                                    accessRecordDto.setUserType((byte) 1);
//                                }
//                            } else if (deviceFaceOrderDto.getType().equals((byte) 3)) {
//                                VisitorDto visitorDto = visitorService.selectById(deviceFaceOrderDto.getHouseholdId());
//                                if (visitorDto != null) {
//                                    accessRecordDto.setUserId(visitorDto.getId());
//                                    accessRecordDto.setName(visitorDto.getName());
//                                    accessRecordDto.setUserType((byte) 3);
//                                }
//                            }
//                        }
//
//                        accessRecordDto.setDoorId(deviceDto.getId());
//                        accessRecordDto.setCreateTime(new Date());
//                        accessRecordDto.setRecordTime(sdf.parse(json.getString("happenTime")));
//                        accessRecordDto.setVillageId(deviceDto.getVillageId());
//                        accessRecordDto.setVillageName(deviceDto.getVillageName());
//                        accessRecordDto.setPicImage(url);
//                        accessRecordDto.setDoorName(deviceDto.getName());
//                        accessRecordDto.setAccessMode((byte) 6);
//                        // 0出 1入
//                        accessRecordDto.setOutOrIn(personDataJson.getByte("ExtEventInOut"));
//
//                        // 如果个性化字段配置了该设备的出入，优先取配置
//                        DeviceSpecialParams.DeviceCategoryentranceguard parseExtStr =
//                                DeviceSpecialParams.parseExtStr(DeviceSpecialParams.DeviceCategoryentranceguard.class, deviceDto.getAttrExt());
//                        if (parseExtStr != null &&  parseExtStr.getOutOrIn() != null) {
//                            accessRecordDto.setOutOrIn(parseExtStr.getOutOrIn());
//                        }
//                        if (accessRecordDto.getUserId() != null || StringUtils.isNotBlank(accessRecordDto.getPicImage())) {
//                            personAccessRecordService.save(accessRecordDto);
//                        }
//                    } catch (Exception e) {
//                        continue;
//                    }
//                }
//
//            }
//
//        }
    }

    private void highTossAct(String data, HikIscConstants.EventEnum eventEnum) {
        JsonNode dataJson = JacksonUtils.parse(data);
        JsonNode eventJson = dataJson.findValue("params").findValue("events");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");

        for (JsonNode jsonNode : eventJson) {
            try {
                String deviceUniqueId = StringUtils.isBlank(jsonNode.get("srcIndex").asText()) ? jsonNode.get("srcParentIndex").asText() : jsonNode.get("srcIndex").asText();
                List<DeviceDto> deviceDtos = deviceService.selectCacheByUniqueId(deviceUniqueId);
                if (CollUtil.isEmpty(deviceDtos)) {
                    continue;
                }

                for (DeviceDto deviceDto : deviceDtos) {
                    ApplicationDto applicationDto = applicationService.selectCacheById(deviceDto.getApplicationId());
                    if (applicationDto == null) {
                        continue;
                    }

                    ApplicationAccessConf.TemplateOfHikIscConf templateOfHikIscConf = ApplicationAccessConf
                            .parseExtStr(ApplicationAccessConf.TemplateOfHikIscConf.class, applicationDto.getAccessConf());

                    assert templateOfHikIscConf != null;
                    MonitorClient instance = HikClientBuilder.builder()
                            .ak(templateOfHikIscConf.getAk())
                            .sk(templateOfHikIscConf.getSk())
                            .host(templateOfHikIscConf.getHost())
                            .build(MonitorClient.class);

                    JsonNode personDataJson = jsonNode.get("data");
                    String picUrl = null;
                    try {
                        JsonNode fielddetection = personDataJson.get("ObjectsThrownDetection");
                        if (fielddetection != null) {
                            for (JsonNode node : fielddetection) {
                                String imageUrl = node.get("Image").get("resourcesContent").asText();
                                if (imageUrl != null && imageUrl.startsWith("http")) {
                                    File file = null;
                                    if (Objects.equals(URLUtils.getHost(imageUrl), templateOfHikIscConf.getHost())) {
                                        //url从isc取得
                                        file = MyFileUtils.downloadToTempDir(imageUrl, false);
                                    } else {
                                        //nvr
                                        DeviceExtraAttrCls.AttrOfIntelligentMonitor attr = DeviceExtraAttrCls.parseExtStr(DeviceExtraAttrCls.AttrOfIntelligentMonitor.class
                                                , deviceDto.getExtraAttr());
                                        if (attr != null && StringUtils.isNotBlank(attr.getManagerUserName())) {
                                            file = MyFileUtils.downloadToTempDirWithBasicAuth(imageUrl, false
                                                    , attr.getManagerUserName(), attr.getManagerPassword());
                                        }
                                    }
                                    if (file != null) {
                                        File rename = FileUtil.rename(file, file.getName() + ".jpg", true, true);
                                        picUrl = StorageKit.uploadToPublicBucketObtainUrl(rename);
                                        FileUtil.del(file);
                                        FileUtil.del(rename);
                                        if (StringUtils.isNotBlank(picUrl)) {
                                            break;
                                        }
                                    }

                                }
                            }
                        }
                    } catch (Exception e) {
                        log.error("hik图片上传", e);
                    }
                    String happenTime = jsonNode.get("happenTime").asText();
                    Date parse = sdf.parse(happenTime);
                    MongoAiEventRecordDto aiEventRecordDto = new MongoAiEventRecordDto();
                    aiEventRecordDto.setTenantId(deviceDto.getTenantId());
                    aiEventRecordDto.setVillageId(deviceDto.getVillageId());
                    aiEventRecordDto.setDeviceCategoryId(deviceDto.getDeviceCategoryId());
                    aiEventRecordDto.setDeviceTypeId(deviceDto.getDeviceTypeId());
                    aiEventRecordDto.setDeviceId(deviceDto.getId());
                    aiEventRecordDto.setDeviceName(deviceDto.getName());
                    if (eventEnum.equals(HIGH_TOSS_ACT)) {
                        aiEventRecordDto.setEventType(AiEventRecordConstants.EventTypeEnum.HIGH_ALTITUDE_PROJECTILES.getEventType());
                    } else if (eventEnum.equals(REGIONAL_INVASION)) {
                        aiEventRecordDto.setEventType(AiEventRecordConstants.EventTypeEnum.REGIONAL_INTRUSION.getEventType());

                    }
                    aiEventRecordDto.setSnapImages(JacksonUtils.toJsonString(Collections.singletonList(picUrl)));
                    aiEventRecordDto.setEventTime(parse);
                    aiEventRecordDto.setLatitude(deviceDto.getLatitude());
                    aiEventRecordDto.setLongitude(deviceDto.getLongitude());
                    AbstractIntelligentMonitorAccessor intelligentMonitorAccessor = AccessorUtils.getIntelligentMonitorAccessor(deviceDto.getDeviceType());
                    Preconditions.checkNotNull(intelligentMonitorAccessor);
                    intelligentMonitorAccessor.aiEventHandler(aiEventRecordDto);
                }

            } catch (Exception e) {
                log.error("海康 高抛事件 处理异常", e);
            }
        }
    }

    private void regionalInvasion(String data, HikIscConstants.EventEnum eventEnum) {
        JsonNode dataJson = JacksonUtils.parse(data);
        JsonNode eventJson = dataJson.findValue("params").findValue("events");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");

        for (JsonNode jsonNode : eventJson) {
            try {
                String deviceUniqueId = StringUtils.isBlank(jsonNode.get("srcIndex").asText()) ? jsonNode.get("srcParentIndex").asText() : jsonNode.get("srcIndex").asText();
                // 区域入侵事件过于频繁
                Integer space = new Random().nextInt(10) + 5;
                boolean setnx = RedisUtils.setnx("HIK_REGIONAL_SPACE_" + deviceUniqueId, deviceUniqueId, space, TimeUnit.MINUTES);
                if (!setnx) {
                    continue;
                }
                List<DeviceDto> deviceDtos = deviceService.selectCacheByUniqueId(deviceUniqueId);
                if (CollUtil.isEmpty(deviceDtos)) {
                    continue;
                }

                for (DeviceDto deviceDto : deviceDtos) {
                    ApplicationDto applicationDto = applicationService.selectCacheById(deviceDto.getApplicationId());
                    if (applicationDto == null) {
                        continue;
                    }

                    ApplicationAccessConf.TemplateOfHikIscConf templateOfHikIscConf = ApplicationAccessConf
                            .parseExtStr(ApplicationAccessConf.TemplateOfHikIscConf.class, applicationDto.getAccessConf());

                    assert templateOfHikIscConf != null;
                    MonitorClient instance = HikClientBuilder.builder()
                            .ak(templateOfHikIscConf.getAk())
                            .sk(templateOfHikIscConf.getSk())
                            .host(templateOfHikIscConf.getHost())
                            .build(MonitorClient.class);

                    JsonNode personDataJson = jsonNode.get("data");
                    String picUrl = null;
                    try {
                        JsonNode fielddetection = personDataJson.get("fielddetection");
                        if (fielddetection != null) {

                            for (JsonNode node : fielddetection) {
                                String imageUrl = node.get("imageUrl").asText();
                                File file = instance.fetchPic(imageUrl);
                                if (file != null) {
                                    picUrl = StorageKit.uploadToPublicBucketObtainUrl(file);
                                    FileUtil.del(file);
                                    if (StringUtils.isNotBlank(picUrl)) {
                                        break;
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        log.error("hik图片上传", e);
                    }
                    String happenTime = jsonNode.get("happenTime").asText();
                    Date parse = sdf.parse(happenTime);
                    MongoAiEventRecordDto aiEventRecordDto = new MongoAiEventRecordDto();
                    aiEventRecordDto.setTenantId(deviceDto.getTenantId());
                    aiEventRecordDto.setVillageId(deviceDto.getVillageId());
                    aiEventRecordDto.setBuildingId(deviceDto.getBuildingId());
                    aiEventRecordDto.setDeviceCategoryId(deviceDto.getDeviceCategoryId());
                    aiEventRecordDto.setDeviceTypeId(deviceDto.getDeviceTypeId());
                    aiEventRecordDto.setDeviceId(deviceDto.getId());
                    aiEventRecordDto.setDeviceName(deviceDto.getName());
                    if (eventEnum.equals(HIGH_TOSS_ACT)) {
                        aiEventRecordDto.setEventType(AiEventRecordConstants.EventTypeEnum.HIGH_ALTITUDE_PROJECTILES.getEventType());
                    } else if (eventEnum.equals(REGIONAL_INVASION)) {
                        aiEventRecordDto.setEventType(AiEventRecordConstants.EventTypeEnum.REGIONAL_INTRUSION.getEventType());

                    }
                    aiEventRecordDto.setSnapImages(JacksonUtils.toJsonString(Collections.singletonList(picUrl)));
                    aiEventRecordDto.setEventTime(parse);
                    aiEventRecordDto.setLatitude(deviceDto.getLatitude());
                    aiEventRecordDto.setLongitude(deviceDto.getLongitude());
                    AbstractIntelligentMonitorAccessor intelligentMonitorAccessor = AccessorUtils.getIntelligentMonitorAccessor(deviceDto.getDeviceType());
                    Preconditions.checkNotNull(intelligentMonitorAccessor);
                    intelligentMonitorAccessor.aiEventHandler(aiEventRecordDto);
                }

            } catch (Exception e) {
                log.error("海康 区域入侵事件 处理异常", e);
            }
        }
    }

    private void licensePlateCapture(String data) {
        JsonNode dataJson = JacksonUtils.parse(data);
        JsonNode eventJson = dataJson.findValue("params").findValue("events");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");

        for (JsonNode jsonNode : eventJson) {
            try {

                String deviceUniqueId = StringUtils.isBlank(jsonNode.get("srcIndex").asText()) ? jsonNode.get("srcParentIndex").asText() : jsonNode.get("srcIndex").asText();
                List<DeviceDto> deviceDtos = deviceService.selectCacheByUniqueId(deviceUniqueId);
                if (CollUtil.isEmpty(deviceDtos)) {
                    continue;
                }

                for (DeviceDto deviceDto : deviceDtos) {
                    JsonNode personDataJson = jsonNode.get("data");
                    String extEventPictureURL = personDataJson.findValue("picUrl").get("vehiclePicUrl").asText();
                    String picUrl = downByUrl(extEventPictureURL);

                    String happenTime = dataJson.get("happenTime").asText();
                    Date parse = sdf.parse(happenTime);
                    MongoAiEventRecordDto aiEventRecordDto = new MongoAiEventRecordDto();
                    aiEventRecordDto.setTenantId(deviceDto.getTenantId());
                    aiEventRecordDto.setVillageId(deviceDto.getVillageId());
                    aiEventRecordDto.setBuildingId(deviceDto.getBuildingId());
                    aiEventRecordDto.setDeviceCategoryId(deviceDto.getDeviceCategoryId());
                    aiEventRecordDto.setDeviceTypeId(deviceDto.getDeviceTypeId());
                    aiEventRecordDto.setDeviceId(deviceDto.getId());
                    aiEventRecordDto.setDeviceName(deviceDto.getName());
                    aiEventRecordDto.setEventType(AiEventRecordConstants.EventTypeEnum.LICENSE_PLATE_CAPTURE.getEventType());
                    aiEventRecordDto.setSnapImages(JacksonUtils.toJsonString(Collections.singletonList(picUrl)));
                    aiEventRecordDto.setEventTime(parse);
                    aiEventRecordDto.setLatitude(deviceDto.getLatitude());
                    aiEventRecordDto.setLongitude(deviceDto.getLongitude());
                    AbstractIntelligentMonitorAccessor intelligentMonitorAccessor = AccessorUtils.getIntelligentMonitorAccessor(deviceDto.getDeviceType());
                    Preconditions.checkNotNull(intelligentMonitorAccessor);
                    intelligentMonitorAccessor.aiEventHandler(aiEventRecordDto);
                }

            } catch (Exception e) {
                log.error("海康 车牌抓拍事件 处理异常", e);
            }
        }
    }

    private void faceCapture(String data) {
        JsonNode dataJson = JacksonUtils.parse(data);
        JsonNode eventJson = dataJson.findValue("params").findValue("events");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");

        for (JsonNode jsonNode : eventJson) {
            try {
                String deviceUniqueId = StringUtils.isBlank(jsonNode.get("srcIndex").asText()) ? jsonNode.get("srcParentIndex").asText() : jsonNode.get("srcIndex").asText();
                List<DeviceDto> deviceDtos = deviceService.selectCacheByUniqueId(deviceUniqueId);
                if (CollUtil.isEmpty(deviceDtos)) {
                    continue;
                }

                for (DeviceDto deviceDto : deviceDtos) {
                    ApplicationDto applicationDto = applicationService.selectCacheById(deviceDto.getApplicationId());
                    if (applicationDto == null) {
                        continue;
                    }

                    ApplicationAccessConf.TemplateOfHikIscConf templateOfHikIscConf = ApplicationAccessConf
                            .parseExtStr(ApplicationAccessConf.TemplateOfHikIscConf.class, applicationDto.getAccessConf());

                    assert templateOfHikIscConf != null;
                    MonitorClient instance = HikClientBuilder.builder()
                            .ak(templateOfHikIscConf.getAk())
                            .sk(templateOfHikIscConf.getSk())
                            .host(templateOfHikIscConf.getHost())
                            .build(MonitorClient.class);

                    JsonNode personDataJson = jsonNode.get("data");
                    String picUrl = null;

                    JsonNode fielddetection = personDataJson.get("captureLibResult");
                    if (fielddetection != null) {

                        for (JsonNode node : fielddetection) {
                            String imageUrl = node.get("imageUrl").asText();
                            File file = instance.fetchPic(imageUrl);
                            if (file != null) {
                                picUrl = StorageKit.uploadToPublicBucketObtainUrl(file);
                                FileUtil.del(file);
                                if (StringUtils.isNotBlank(picUrl)) {
                                    break;
                                }
                            }
                        }
                    }

                    String happenTime = dataJson.get("happenTime").asText();
                    Date parse = sdf.parse(happenTime);
                    MongoAiEventRecordDto aiEventRecordDto = new MongoAiEventRecordDto();
                    aiEventRecordDto.setTenantId(deviceDto.getTenantId());
                    aiEventRecordDto.setVillageId(deviceDto.getVillageId());
                    aiEventRecordDto.setBuildingId(deviceDto.getBuildingId());
                    aiEventRecordDto.setDeviceCategoryId(deviceDto.getDeviceCategoryId());
                    aiEventRecordDto.setDeviceTypeId(deviceDto.getDeviceTypeId());
                    aiEventRecordDto.setDeviceId(deviceDto.getId());
                    aiEventRecordDto.setDeviceName(deviceDto.getName());
                    aiEventRecordDto.setEventType(AiEventRecordConstants.EventTypeEnum.PERSON_FACE_CAPTURE.getEventType());
                    aiEventRecordDto.setSnapImages(JacksonUtils.toJsonString(Collections.singletonList(picUrl)));
                    aiEventRecordDto.setEventTime(parse);
                    aiEventRecordDto.setLatitude(deviceDto.getLatitude());
                    aiEventRecordDto.setLongitude(deviceDto.getLongitude());
                    AbstractIntelligentMonitorAccessor intelligentMonitorAccessor = AccessorUtils.getIntelligentMonitorAccessor(deviceDto.getDeviceType());
                    Preconditions.checkNotNull(intelligentMonitorAccessor);
                    intelligentMonitorAccessor.aiEventHandler(aiEventRecordDto);
                }

            } catch (Exception e) {
                log.error("海康 人脸抓拍事件 处理异常", e);
            }


        }
    }

    private void visFaceOpenLock(String data) {
//        LOGGER.info("海康可视对讲人脸开锁事件回调 {} 时间 {}", data, DateUtils.getCurrentDateStr(DateUtils.FormatType.COMMON));
//        JSONObject jsonObject = JacksonUtils.parse(data);
//        JSONArray jsonArray =
//                jsonObject.getJSONObject("params").getJSONArray("events");
//
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
//
//        for (Object o : jsonArray) {
//            JSONObject json = (JSONObject) o;
//            String deviceUniqueId = StringUtils.isBlank(json.getString("srcIndex")) ? json.getString("srcParentIndex") : json.getString("srcIndex");
//            DeviceDto deviceDto = deviceService.selectCacheDevice(deviceUniqueId);
//            if (deviceDto == null) {
//                continue;
//            }
//            ApplicationDto ApplicationDto = applicationService.selectCacheById(deviceDto.getApplicationId());
//            if (ApplicationDto == null) {
//                continue;
//            }
//            try {
//                JSONObject personDataJson = json.getJSONObject("data");
//                String extEventPictureURL = personDataJson.getString("ExtEventPictureURL");
//                String svrIndexCode = personDataJson.getString("svrIndexCode");
//                String url = null;
//                try {
//                    url = hikGateService.getPictures(deviceDto.getApplicationId(), svrIndexCode, extEventPictureURL);
//                } catch (Exception e) {
//                    LOGGER.error("hik可视对讲抓拍获取异常", e);
//                }
//                String extEventPersonNo = personDataJson.getString("ExtEventPersonNo");
//
//                HouseHoldDto houseHoldDto = null;
//                DeviceFaceOrderDto deviceFaceOrderDto = deviceFaceOrderService.selectByDeviceIdAndFaceCode(deviceDto.getId(), extEventPersonNo);
//                if (deviceFaceOrderDto != null) {
//                    houseHoldDto = houseHoldService.selectById(deviceFaceOrderDto.getHouseholdId());
//                }
//
//                AccessRecordDto accessRecordDto = new AccessRecordDto();
//                accessRecordDto.setDoorId(deviceDto.getId());
//                accessRecordDto.setCreateTime(new Date());
//                accessRecordDto.setRecordTime(sdf.parse(json.getString("happenTime")));
//                if (houseHoldDto != null && Objects.equals(houseHoldDto.getVillageId(), deviceDto.getVillageId())) {
//                    accessRecordDto.setUserId(houseHoldDto.getId());
//                    accessRecordDto.setName(houseHoldDto.getName());
//                }
//                accessRecordDto.setVillageId(deviceDto.getVillageId());
//                accessRecordDto.setVillageName(deviceDto.getVillageName());
//                accessRecordDto.setPicImage(url);
//                accessRecordDto.setDoorName(deviceDto.getName());
//                accessRecordDto.setAccessMode((byte) 6);
//                accessRecordDto.setOutOrIn(personDataJson.getByte("ExtEventInOut"));
//
//                // 如果个性化字段配置了该设备的出入，优先取配置
//                DeviceSpecialParams.DeviceCategoryentranceguard parseExtStr =
//                        DeviceSpecialParams.parseExtStr(DeviceSpecialParams.DeviceCategoryentranceguard.class, deviceDto.getAttrExt());
//                if (parseExtStr != null &&  parseExtStr.getOutOrIn() != null) {
//                    accessRecordDto.setOutOrIn(parseExtStr.getOutOrIn());
//                }
//
//                if (accessRecordDto.getUserId() != null || StringUtils.isNotBlank(accessRecordDto.getPicImage())) {
//                    personAccessRecordService.save(accessRecordDto);
//                }
//            } catch (Exception e) {
//                LOGGER.error("Exception", e);
//                continue;
//            }
//        }
    }

    private void villageingLotAdmission(String data) {
//        LOGGER.info("海康停车场入场放行事件回调 {} 时间 {}", data, DateUtils.getCurrentDateStr(DateUtils.FormatType.COMMON));
//        JSONObject jsonObject = JacksonUtils.parse(data);
//        JSONArray jsonArray =
//                jsonObject.getJSONObject("params").getJSONArray("events");
//
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
//
//        for (Object o : jsonArray) {
//            JSONObject json = (JSONObject) o;
//            try {
//                String srcIndex = json.getString("srcIndex");
//                JSONObject dataJson = json.getJSONObject("data");
//                String svrIndexCode = dataJson.getString("svrIndex");
//                if (svrIndexCode == null) {
//                    break;
//                }
//                DeviceDto deviceDto = deviceService.selectByUniqueId(srcIndex);
//                if (deviceDto == null) {
//                    throw new NullPointerException("没有该设备");
//                }
//                CarRecordDto carRecordDto = new CarRecordDto();
//                carRecordDto.setEntranceCode(srcIndex);
//                carRecordDto.setEntranceName(deviceDto.getName());
//                carRecordDto.setInOutStatus((byte) dataJson.getIntValue("inoutType"));
//                carRecordDto.setPlateNo(dataJson.getString("plateNo"));
//                carRecordDto.setPlateCode((byte) 1);
//                if (dataJson.getIntValue("plateColor") < 5) {
//                    carRecordDto.setPlateColor((byte) (dataJson.getIntValue("plateColor") + 2));
//                } else {
//                    carRecordDto.setPlateColor((byte) 1);
//                }
//                carRecordDto.setCarType((byte) 1);
//                carRecordDto.setRecordTime(sdf.parse(json.getString("happenTime")));
//                carRecordDto.setCreateTime(new Date());
//                String vehiclePicUrl = dataJson.getJSONObject("picUrl").getString("vehiclePicUrl");
//                String url = null;
//                try {
//                    url = hikGateService.getPictures(deviceDto.getApplicationId(), svrIndexCode, vehiclePicUrl);
//                } catch (Exception e) {
//                    LOGGER.error("hik车辆图片获取异常", e);
//                }
//                carRecordDto.setPicImage(url);
//                if (deviceDto.getVillageId() != null) {
//                    carRecordDto.setVillageId(deviceDto.getVillageId());
//                }
//                carRecordService.save(carRecordDto);
//            } catch (Exception e) {
//                LOGGER.error("Exception", e);
//                continue;
//            }
//        }
    }

    private void villageingLotAppearance(String data) {
//        LOGGER.info("海康停车场出场放行事件回调 {} 时间 {}", data, DateUtils.getCurrentDateStr(DateUtils.FormatType.COMMON));
//        JSONObject jsonObject = JacksonUtils.parse(data);
//        JSONArray jsonArray =
//                jsonObject.getJSONObject("params").getJSONArray("events");
//
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
//
//        for (Object o : jsonArray) {
//            JSONObject json = (JSONObject) o;
//            try {
//                String srcIndex = json.getString("srcIndex");
//                JSONObject dataJson = json.getJSONObject("data");
//                String svrIndexCode = dataJson.getString("svrIndex");
//                if (svrIndexCode == null) {
//                    break;
//                }
//                DeviceDto deviceDto = deviceService.selectCacheDevice(srcIndex);
//                if (deviceDto == null) {
//                    throw new NullPointerException("没有该设备");
//                }
//                CarRecordDto carRecordDto = new CarRecordDto();
//                carRecordDto.setEntranceCode(srcIndex);
//                carRecordDto.setEntranceName(deviceDto.getName());
//                carRecordDto.setInOutStatus((byte) dataJson.getIntValue("inoutType"));
//                carRecordDto.setPlateNo(dataJson.getString("plateNo"));
//                carRecordDto.setPlateCode((byte) 1);
//                if (dataJson.getIntValue("plateColor") < 5) {
//                    carRecordDto.setPlateColor((byte) (dataJson.getIntValue("plateColor") + 2));
//                } else {
//                    carRecordDto.setPlateColor((byte) 1);
//                }
//                carRecordDto.setCarType((byte) 1);
//                carRecordDto.setRecordTime(sdf.parse(json.getString("happenTime")));
//                carRecordDto.setCreateTime(new Date());
//                String vehiclePicUrl = dataJson.getJSONObject("picUrl").getString("vehiclePicUrl");
//                String url = null;
//                try {
//                    url = hikGateService.getPictures(deviceDto.getApplicationId(), svrIndexCode, vehiclePicUrl);
//                } catch (Exception e) {
//                    LOGGER.error("hik车辆图片获取异常", e);
//                }
//                carRecordDto.setPicImage(url);
//                if (deviceDto.getVillageId() != null) {
//                    carRecordDto.setVillageId(deviceDto.getVillageId());
//                }
//                carRecordService.save(carRecordDto);
//            } catch (Exception e) {
//                LOGGER.error("Exception", e);
//                continue;
//            }
//        }
    }

    private String downByUrl(String url) {
        // 可直接下载的地址
        File tempFile = MyFileUtils.downloadToTempDir(url, false);
        String u = MinIOUtils.putObjectToBucketObtainObject(MinIOClient.DEFAULT_PUBLIC_BUCKET, tempFile, false);
        return u;
    }
}
